const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
const cors = require('cors');

const imgUploadRouter = require('./routes/upload');
const userRouter = require('./routes/users');
const customerInfoRouter = require('./routes/customerInfo');
const sessionRouter = require('./routes/sessions');
const registRouter = require('./routes/regist');
const noticeRouter = require('./routes/notice');
const employeeRouter = require('./routes/employee');
const vipRouter = require('./routes/vip');
const achievementRouter = require('./routes/achievement');
const beautyServiceRouter = require('./routes/beautyService');
const materialRouter = require('./routes/material');
const stockRouter = require('./routes/stock');
const orderRouter = require('./routes/order');
const purchaseRouter = require('./routes/purchase');
const assessRouter = require('./routes/assess');
const buyerRouter = require('./routes/buyer');
const alipayRouter = require('./routes/alipay');
const costRouter = require('./routes/cost');
const { verifyToken } = require('./utils/token');

const app = express();

//数据库连接
mongoose.connect('mongodb://localhost:27017/CarBeautySystem');

//使用cors跨域
const corsConfig = {
  origin:'http://124.222.96.201:9000',
  credentials:true,
}
//使用默认
app.use(cors())
//或修改默认配置
app.use(cors(corsConfig))

app.get('/', function (req, res) {
  res.send('<h1>Car Beauty System Service</h1>');
});

app.use(express.static(path.join(__dirname,'public')));// 托管静态资源
app.use(express.json()); // for parsing application/json  当提交的数据为json格式时
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded 当提交的数据是普通文本格式时

app.use('/api/session', sessionRouter);//登录
app.use('/api/regist', registRouter);//注册
app.use('/api/imgUpload',imgUploadRouter)

// 根据 token 验证用户身份信息
app.use((req, res, next) => {
  // 从请求头中获取用户的 token 数据
  const token = req.get('x-token')
  //const user = req.get('user')
  try {
    // 验证 token 是否合法
    const payload = verifyToken(token)
    // if( user !== payload.username){
    //   throw new Error
    // }
    console.log('保存在 token 中的数据：', payload)
    next()
  } catch (error) {
    //console.log('token错误：', error)
    res.json({
      code: 400,
      data: null,
      message: 'token 认证失败，请重新登录！'
    })
  }
})

app.use('/api/users',userRouter);
app.use('/api/customerInfo',customerInfoRouter);
app.use('/api/notice',noticeRouter);
app.use('/api/employee',employeeRouter);
app.use('/api/vip',vipRouter);
app.use('/api/achievement',achievementRouter);
app.use('/api/beautyService',beautyServiceRouter);
app.use('/api/material',materialRouter);
app.use('/api/stock',stockRouter);
app.use('/api/order',orderRouter);
app.use('/api/purchase',purchaseRouter);
app.use('/api/assess',assessRouter);
app.use('/api/buyer',buyerRouter);
app.use('/api/cost',costRouter);
app.use('/api/alipay',alipayRouter);

app.listen(8190,() => console.log('Serve run at http://localhost:8190'));